<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Cumulative Layout Shift</title>
    <link href="./偏移布局-Cumulative-Layout-Shift.css" rel="stylesheet">
    <link href="http://localhost:10001/css/slow2.css" rel="stylesheet">
  </head>
  <body>
      <div class="slow">这里会偏移</div>
      <button class="cancel-order">取消下单</button>
      <button class="order">我要下单</button>
    <script>
      try {
        let cumulativeLayoutShiftScore = 0;

        const observer = new PerformanceObserver((list) => {
          for (const entry of list.getEntries()) {
            console.log(entry, "entry");
            if (!entry.hadRecentInput) {
              cumulativeLayoutShiftScore += entry.value;
            }
          }
        });

        observer.observe({ type: "layout-shift", buffered: true });

        document.addEventListener("visibilitychange", (arg) => {
          console.log("visibilitychange", arg);
          if (document.visibilityState === "hidden") {
            observer.takeRecords();
            observer.disconnect();

            console.log("CLS:", cumulativeLayoutShiftScore);
          }
        });
      } catch (e) {
        // Do nothing if the browser doesn't support this API.
      }
    </script>
  </body>
</html>
